<template>
	<layout>
		<el-form>
			{{ $route.params.id }}
			<el-form-item label="商品名称">
				<el-input placeholder="" v-model="form.name"></el-input>
			</el-form-item>

			<el-form-item label="价格">
				<el-input placeholder="" v-model="form.price"></el-input>
			</el-form-item>
			<el-form-item label="分类">
				<el-select v-model="form.cate_id" placeholder="请选择">
					<el-option
						v-for="(item, index) in cateList"
						:value="item.id"
						:label="item.name"
					></el-option>
					<el-option>2</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="图片">
				<el-upload
					:headers="headers"
					:on-success="success1"
					action="http://localhost:7002/img/upload"
					list-type="picture-card"
				>
					<i class="el-icon-plus"></i>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button @click="save">保存</el-button>
			</el-form-item>
		</el-form>
	</layout>
</template>

<script>
export default {
	data() {
		return {
			form: {
				name: '',
				price: '',
				cate_id: '',
			},

			cateList: [],
			headers: {
				//令牌校检
				authorization: localStorage.getItem('token'),
			},
		}
	},
	created() {
		//编辑以获取相应ID的数据
		if (this.$route.params.id) {
			this.$http
				.get(`/product/get?id=${this.$route.params.id}`)
				.then((res) => {
					if (res.errcode == 0) {
						this.form = res.data
					}
				})
		}
		this.$http.get('/cate/select').then((res) => {
			if (res.errcode == 0) {
				this.cateList = res.data
			}
		})
	},
	methods: {
		success1(res) {
			if (res.errcode == 0) {
				this.form.img_id = res.data.id
			}
		},
		save() {
			//有ID就是编辑
			if (this.$route.params.id) {
				this.$http.post('/product/update', this.form).then((res) => {
					if (res.errcode == 0) {
						this.$router.back()
					}
				})
			} else {
				this.$http.post('/product/insert', this.form).then((res) => {
					if (res.errcode == 0) {
						this.$router.back()
					}
				})
			}
		},
	},
}
</script>

<style></style>
